package com.snnsh.kjb.lottery.util;

import com.snnsh.kjb.lottery.po.ProductPO;
import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * packageName com.snnsh.kjb.lottery.util
 *
 * @author wick
 * @version V1.0.0
 * @date 2025/5/27
 */
public class Dom4jXMLManager {

    private static final DocumentFactory docFactory = DocumentFactory.getInstance();

    private static final String DEFAULT_DATA_PATH = "lottery_data";

    /**
     * @description
     * @param prodList:
     * @param filePath:
     * @return void
     * @author wick
     * @deprecated 特定的PO
     * @see Dom4jXMLManager#write2Xml(java.util.List, java.lang.Class, java.lang.String)
     * @date 2025/5/27
     */
    @Deprecated
    public static void writeProduct2Xml(List<ProductPO> prodList, String filePath){
        filePath = DEFAULT_DATA_PATH + File.separator + filePath;
        Document doc = docFactory.createDocument("utf-8");  //创建Document实例
        Element rootEle = docFactory.createElement("products");    //创建文档根元素
        doc.setRootElement(rootEle);   //设置文档的根元素
        /* 实现将Document对象保存为xml文件 */
        String classPath = Tools.getClassPath();    //获取类路径
        /* 创建目标要保存写入的xml文件 */
        File xmlFile = new File(classPath + File.separator + filePath);
        if(CollectionUtils.isEmpty(prodList)){
            //直接删除文件
            if(xmlFile.exists()){
                xmlFile.delete();
            }
        }
        if (!CollectionUtils.isEmpty(prodList)){
            for (ProductPO prod:prodList) {
                Element prodEle = docFactory.createElement("product");  //循环创建rootEle的子元素employee
                Element codeEle = docFactory.createElement("id");     //循环创建empEle下的子元素code
                codeEle.setText(prod.getId()+"");      //设置codeEle元素的文本值
                Element nameEle = docFactory.createElement("name");     //循环创建empEle下的子元素name
                nameEle.setText(prod.getName());
                Element weightEle = docFactory.createElement("weight");
                weightEle.setText(new BigDecimal(prod.getWeight()).setScale(2, RoundingMode.HALF_UP)+"");
                Element flagEle = docFactory.createElement("flag");
                flagEle.setText(prod.getFlag()+"");

                /* 将子元素添加到empEle中 */
                prodEle.add(codeEle);
                prodEle.add(nameEle);
                prodEle.add(weightEle);
                prodEle.add(flagEle);
                rootEle.add(prodEle);
            }
            if(!xmlFile.exists()){
                xmlFile.getParentFile().mkdirs();
            }
            /* 创建Writer */
            Writer writer = null;
            try {
                writer = new FileWriter(xmlFile);
                /* 创建XMLWriter */
                XMLWriter xmlWriter = new XMLWriter(writer, OutputFormat.createPrettyPrint());
                xmlWriter.write(doc);   //保存为xml目标文件
            } catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * @description
     * @param filePath: 
     * @return List<ProductPO>
     * @author wick
     * @date 2025/5/27
     * @deprecated 有更通用的
     * @see Dom4jXMLManager#getFromXML(java.lang.String, java.lang.Class)
     */
    @Deprecated
    public static List<ProductPO> getProductFromXML(String filePath){
        filePath = DEFAULT_DATA_PATH + File.separator + filePath;
        List<ProductPO> prodList  = new LinkedList<>();
        String classPath = Tools.getClassPath();//获取类路径
        /* 基于路径建立文件对象 */
        File xmlFile = new File(classPath +filePath);
        if(!xmlFile.exists()){
            return prodList;
        }
        Reader reader = null;
        try {
            reader = new FileReader(xmlFile);  //基于xml文件建立文件流
            SAXReader saxReader = new SAXReader();  //建立SAXReader对象
            Document doc = saxReader.read(reader); //读取xml文件
            if (doc != null){
                Element rootEle = doc.getRootElement();   //获取根元素
                List<Element> prod_List = rootEle.elements("product");   //获取所有根元素下的所有子元素emplopyee
                for (Element e:prod_List){

                    ProductPO prodObj = new ProductPO();
                    String codeText = e.element("id").getText();  //获取元素code文本
                    prodObj.setId(Integer.valueOf(codeText));

                    String nameText = e.element("name").getText();  //获取元素name文本
                    prodObj.setName(nameText);
                    String weightText = e.element("weight").getText();
                    prodObj.setWeight(Float.valueOf(weightText));
                    String flagText = e.element("flag").getText();
                    prodObj.setFlag(Integer.valueOf(flagText));
                    prodList.add(prodObj); //添加员工对象到List集合中
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return prodList;
    }


    public static void main(String[] args) {
        String realFilePath = getRealFilePath("abc.xml");
        System.out.println(realFilePath);
    }
    /**
     * @description
     * @param list: 
     * @param poClass:
     * @param filePath: 
     * @return void
     * @author wick
     * @date 2025/5/27
     */
    public static <T> void write2Xml(List<T> list,Class<T> poClass,String filePath){
        String className = poClass.getSimpleName();
        String rootElementName = className+"List";
        Document doc = docFactory.createDocument("utf-8");
        Element rootEle = docFactory.createElement(rootElementName);
        doc.setRootElement(rootEle);
        File xmlFile = new File(getRealFilePath(filePath));
        if(CollectionUtils.isEmpty(list)){
            //直接删除文件
            if(xmlFile.exists()){
                xmlFile.delete();
            }
        }
        else {
            Field[] declaredFields = poClass.getDeclaredFields();

            for (T po:list) {
                Element prodEle = docFactory.createElement(className);
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    declaredField.setAccessible(true);
                    try {
                        Object o = declaredField.get(po);
                        if(o!=null) {
                            if(Float.class.equals(o.getClass())){
                                o = new BigDecimal(o+"").setScale(2,RoundingMode.HALF_UP);
                            }
                            Element childEle = docFactory.createElement(name);
                            childEle.setText(o+"");
                            prodEle.add(childEle);
                        }
                    }
                    catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                rootEle.add(prodEle);
            }
        }
        if(!xmlFile.exists()){
            xmlFile.getParentFile().mkdirs();
        }
        /* 创建Writer */
        Writer writer = null;
        try {
            writer = new FileWriter(xmlFile);
            /* 创建XMLWriter */
            XMLWriter xmlWriter = new XMLWriter(writer, OutputFormat.createPrettyPrint());
            xmlWriter.write(doc);   //保存为xml目标文件
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * @description 得到所有的记录
     * @param filePath: 
     * @param poClass: 
     * @return List<T>
     * @author wick
     * @date 2025/5/27
     */
    public static <T> List<T> getFromXML(String filePath,Class<T> poClass) {
        List<T> list  = new LinkedList<>();
        File xmlFile = new File(getRealFilePath(filePath));
        if(!xmlFile.exists()){
            return list;
        }
        Reader reader = null;
        try{
            reader = new FileReader(xmlFile);
            SAXReader saxReader = new SAXReader();  //建立SAXReader对象
            Document doc = saxReader.read(reader); //读取xml文件
            if (doc != null){
                Element rootEle = doc.getRootElement();   //获取根元素
                List<Element> po_List = rootEle.elements(poClass.getSimpleName());   //获取所有根元素下的所有子元素emplopyee
                Field[] declaredFields = poClass.getDeclaredFields();
                for (Element e:po_List){
                    T poObj = poClass.newInstance();
                    for (Field declaredField : declaredFields) {
                        String text = "";
                        Element element = e.element(declaredField.getName());
                        if(element!=null){
                            text = e.element(declaredField.getName()).getText();
                        }
                        if(ObjectUtils.isEmpty(text)){
                            continue;
                        }
                        declaredField.setAccessible(true);
                        if(declaredField.getType().equals(Integer.class)) {
                            declaredField.set(poObj,Integer.valueOf(text));
                        }
                        else if(declaredField.getType().equals(String.class)){
                            declaredField.set(poObj,text);
                        }
                        else if(declaredField.getType().equals(Float.class)) {
                            declaredField.set(poObj,Float.valueOf(text));
                        }
                    }
                    list.add(poObj); //添加员工对象到List集合中
                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    public static String getRealFilePath(String filePath) {
        String projectPath = System.getProperty("user.dir");
        String realFilePath = projectPath + File.separator + DEFAULT_DATA_PATH + File.separator + filePath;
        System.out.println("路径 user.dir : " + realFilePath);
        return realFilePath;
    }
}
